# Copyright 2021-2023 @ Shenzhen Bay Laboratory &
#                       Peking University &
#                       Huawei Technologies Co., Ltd
#
# This code is a part of Cybertron package.
#
# The Cybertron is open-source software based on the AI-framework:
# MindSpore (https://www.mindspore.cn/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""
Basic Neural network layer
"""

from typing import Union, List, Optional, Dict, Any
from collections import OrderedDict

import torch
from torch import nn, Tensor
from torch.nn import Module

from .utils import get_integer, get_initializer, GLOBAL_DEVICE, get_arguments
from .activation import get_activation


__all__ = [
    "Dense",
    "MLP",
    "Residual",
    "PreActDense",
    "PreActResidual",
    "SeqPreActResidual",
]

nn.Linear
class Dense(Module):
    """Dense (fully connected) layer with customizable initialization and activation.

    Args:
        in_features: Number of input features
        out_features: Number of output features
        has_bias: Whether to include a bias term
        weight_init: Weight initialization method or tensor
        bias_init: Bias initialization method or tensor
        activation: Activation function or its name
    """
    def __init__(self,
                 in_features: int,
                 out_features: int,
                 has_bias: bool = True,
                 weight_init: Union[Tensor, str] = 'xavier_uniform',
                 bias_init: Union[Tensor, str] = 'zeros',
                 activation: Union[Module, str] = None,
                 ):

        super().__init__()
        self.device = GLOBAL_DEVICE()

        weight_init = get_initializer(weight_init, in_features, out_features, dtype=torch.float32, device=self.device)
        bias_init = get_initializer(bias_init, out_features, dtype=torch.float32, device=self.device)
        self.weight = nn.Parameter(weight_init,requires_grad=True)
        if has_bias:
            self.bias = nn.Parameter(bias_init,requires_grad=True)
        else:
            self.bias = torch.tensor(0,dtype=torch.float32,device=self.device)
        self.activate = get_activation(activation)

    def forward(self, inputs: Tensor) -> Tensor:
        x = torch.matmul(inputs,self.weight)+self.bias
        if self.activate:
            x = self.activate(x)
        return x

class MLP(Module):
    """Multi-layer perceptron with customizable layers and activations.

    Args:
        in_features: Number of input features
        out_features: Number of output features
        layer_dims: List of hidden layer dimensions
        activation: Activation function or its name
        weight_init: Weight initialization method or tensor
        bias_init: Bias initialization method or tensor
        use_last_activation: Whether to apply activation to the output layer
    """
    def __init__(self,
                 in_features: int,
                 out_features: int,
                 layer_dims: List[int] = None,
                 activation: Union[Module, str] = None,
                 weight_init: Union[Tensor, str] = 'xavier_uniform',
                 bias_init: Union[Tensor, str] = 'zeros',
                 use_last_activation: bool = False,
                 **kwargs
                 ):
        super().__init__()
        self._kwargs = get_arguments(locals(), kwargs)

        self.n_in = get_integer(in_features)
        self.n_out = get_integer(out_features)
        self.device = GLOBAL_DEVICE()

        # get list of number of dimensions in input, hidden & output layers
        if (layer_dims is None) or (not layer_dims):
            self.mlp = Dense(in_features=indim, out_features=ldim, has_bias=True, 
                             weight_init=weight_init, bias_init=bias_init, activation=activation)
        else:
            # assign a Dense layer (with activation function) to each hidden layer
            nets = OrderedDict()
            indim = self.n_in
            i = 0
            for ldim in layer_dims:
                # nets.append(Dense(indim, ldim,activation=activation))
                nets['Dense{}'.format(i)] = Dense(in_features=indim, out_features=ldim, has_bias=True, weight_init=weight_init, bias_init=bias_init, 
                                                  activation=activation)
                indim = ldim
                i += 1
            
            # assign a Dense layer to the output layer
            if use_last_activation and activation is not None:
                nets['Dense{}'.format(i)] = Dense(in_features=ldim, out_features=self.n_out, has_bias=True, weight_init=weight_init, bias_init=bias_init, 
                                                  activation=activation)
            else:
                nets['Linear{}'.format(i)] = nn.Linear(in_features=ldim, out_features=self.n_out,bias=True, device=self.device)

            # put all layers together to make the network
            self.mlp = nn.Sequential(nets)

    def forward(self, x: Tensor):
        y = self.mlp(x)
        return y


class Residual(Module):
    """Residual block with customizable hidden layers.

    Args:
        features: Number of input/output features (must be the same)
        activation: Activation function or its name
        n_hidden: Number of hidden layers
    """
    def __init__(self,
                 features: int,
                 activation: Union[Module, str],
                 n_hidden: int = 1,
                 **kwargs
                 ):
        super().__init__()
        self._kwargs = get_arguments(locals(), kwargs)

        self.device = GLOBAL_DEVICE()
        dim = get_integer(features)
        n_hidden = get_integer(n_hidden)
        if n_hidden > 0:
            hidden_layers = [dim] * n_hidden
            self.nonlinear = MLP(dim, dim, hidden_layers, activation=activation)
        else:
            self.nonlinear = Dense(dim, dim, activation=activation)

    def forward(self, x: Tensor) -> Tensor:
        return x + self.nonlinear(x)


class PreActDense(Module):
    """Pre-activation dense layer (activation before linear transformation).

    Args:
        in_features: Number of input features
        out_features: Number of output features
        activation: Activation function or its name
    """
    def __init__(self,
                 in_features: int,
                 out_features: int,
                 activation: Union[Module, str],
                 **kwargs
                 ):
        super().__init__()
        self._kwargs = get_arguments(locals(), kwargs)

        self.device = GLOBAL_DEVICE()
        self.activation = get_activation(activation)
        self.dense = Dense(in_features, out_features, has_bias=True)

    def forward(self, x: Tensor) -> Tensor:
        x = self.activation(x)
        return self.dense(x)


class PreActResidual(Module):
    """Pre-activation residual block.

    Args:
        features: Number of input/output features (must be the same)
        activation: Activation function or its name
    """
    def __init__(self,
                 features: int,
                 activation: Union[Module, str],
                 **kwargs
                 ):
        super().__init__()
        self._kwargs = get_arguments(locals(), kwargs)

        self.device = GLOBAL_DEVICE()
        self.preact_dense1 = PreActDense(features, features, activation)
        self.preact_dense2 = PreActDense(features, features, activation)

    def forward(self, x: Tensor) -> Tensor:
        x1 = self.preact_dense1(x)
        x2 = self.preact_dense2(x1)
        return x + x2


class SeqPreActResidual(Module):
    """Sequential pre-activation residual blocks.

    Args:
        dim: Number of input/output features (must be the same)
        activation: Activation function or its name
        n_res: Number of residual blocks
    """
    def __init__(self,
                 dim: int,
                 activation: Union[Module, str],
                 n_res: int,
                 **kwargs
                 ):
        super().__init__()
        self._kwargs = get_arguments(locals(), kwargs)
        
        self.device = GLOBAL_DEVICE()
        self.sequential = nn.Sequential(
            OrderedDict([['PreActResidual{}'.format(_),PreActResidual(dim, activation)] for _ in range(n_res)])
        )

    def forward(self, x: Tensor) -> Tensor:
        return self.sequential(x)
